<?php
namespace App\Controller;
use Common\Controller\AppbaseController;
use Common\Controller\AppmemberbaseController;
use Common\Controller\AppuserbaseController;
use Think\Model;

class IndexController extends AppuserbaseController {

    /**
     * 根据分类id获取轮播图，1是首页
     */
	public function getSlidesByCat(){
		$cat=I('cat',0,'intval');
        if(!$cat){
            $this->jsonReturn(0,'缺少参数');
        }
		$slides=M('Slide')->where(['slide_cid'=>$cat,'slide_status'=>1])->field('slide_id as id,slide_pic')->select();
        if($slides){
            $host=$this->uploadPre;
            foreach ($slides as &$slide){
                $slide['slide_pic']=$host.$slide['slide_pic'];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$slides);
        }else{
            $slide=M('Slide')->where(['slide_id'=>1])->field('slide_id as id,slide_pic')->select();
            $this->jsonUnslashesReturn(1,'获取成功',$slide);
        }
	}

    /**
     * 首页轮播详情页
     */
    public function slideDetail(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $slide=M('Slide')->where(['slide_id'=>$id,'slide_status'=>1])->find();
        if($slide){
            $this->assign('slide',$slide);
            $this->display('slideDetail');
        }else{
            $this->error('轮播图不存在');
        }
    }

    /**
     * 首页获取城市
     */
    public function getCity(){
        $lat=I('lat');
        $long=I('lng');
        if(!$lat||!$long){
            $this->jsonReturn(0,'请开启定位');
        }
        $city=$this->getSite($lat,$long);
        if($city!==false){
            $this->jsonReturn(1,'获取成功',$city['name']);
        }else{
            $this->jsonReturn(0,'获取失败');
        }
    }

    //获取商户列表
    public function getBusinesses(){
        $lat=I('lat');
        $long=I('lng');
        $page=I('page',0,'intval');
        $type=I('type',0,'intval');
        if(!$lat||!$long||$page<=0||!$type){
            $this->jsonReturn(0,'请开启定位');
        }
        //获取经营范围
        $scope=$this->getScopeTypeByType($type);
        $start=($page-1)*$this->pageLimit;
        //获取城市名和id
        $region=$this->getSite($lat,$long);
        $region_id=$region['id'];
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        //获取城市下区域id
        $region_ids=M('Region')->where(['pid'=>$region_id])->select();
        $region_ids=array_column($region_ids,'id');
        //20000米内，按星级排序
        $businesses=M('Business')
            ->alias('b')
            ->where(['b.status'=>1,'b.is_checked'=>1,'region_id'=>['in',$region_ids],'scope_id'=>['in',$scope],"$sql"=>['ELT',200000]])
            ->join('LEFT JOIN __REGION__ as r ON r.id=b.region_id')
            ->field("b.id,b.type,r.name as city,b.name,points,logo,good_at,collect_num,visit_num,$sql as distance,visit,b.address")
            ->order('points DESC,distance')->limit($start,$this->pageLimit+1)->select();
        if($businesses){
            //加前缀,默认商家logo
            foreach ($businesses as &$business){
                $business['logo']=empty($business['logo'])?"":$this->uploadPre.$business['logo'];
                $business['city']=$region['name'].$business['city'];
            }
            //检测是否是最后一页
            $businesses=$this->checkEndPage($businesses);
            $this->jsonUnslashesReturn(1,'获取成功',$businesses);
        }else{
            $this->jsonReturn(1,'没有商家了',(object)[]);
        }
    }

    //获取店铺信息详情
    public function getBusinessData(){
        $lat=I('lat');
        $long=I('lng');
        $id=I('id',0,'intval');
        if(!$lat||!$long||!$id){
            $this->jsonReturn(0,'请开启定位');
        }
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $business=M('Business')->where(['id'=>$id,'status'=>1,'is_checked'=>1])->field("id,is_prepared,url,type,name,points,good_at,collect_num,visit_num,$sql as distance,address,phone,acreage,people_number,years,advantage,lat,`long` as lng,create_time")->find();
        if($business){
            $token=I('token');
            $collected='0';
            if($token){
                $user=lt_get_user_by_token($token);
                if($user && $user['status']==1){
                    $collect=M('BusinessCollection')->where(['user_id'=>$user['id'],'business_id'=>$business['id']])->find();
                    if($collect){
                        $collected='1';
                    }
                }
            }
            $business['collected']=$collected;
            $this->jsonReturn(1,'获取成功',$business);
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取商家轮播图
     */
    public function getBusinessSlides(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $slides=M('BusinessSlide')->where(['business_id'=>$id])->field('image')->select();
            M('Business')->where(['id'=>$id])->setInc('visit_num');
            if($slides){
                foreach ($slides as &$slide){
                    $slide['image']=empty($slide['image'])?'':$this->uploadPre.$slide['image'];
                }
                $this->jsonUnslashesReturn(1,'获取成功',$slides);
            }else{
                $this->jsonUnslashesReturn(1,'获取成功',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取商户技师
     */
    public function getBusinessTech(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $technicians=M('BusinessTech')->where(['business_id'=>$id])->field('name,avatar')->select();
            if($technicians){
                foreach ($technicians as &$technician){
                    $technician['avatar']=empty($technician['avatar'])?"":$this->uploadPre.$technician['avatar'];
                }
                $this->jsonUnslashesReturn(1,'获取成功',$technicians);
            }else{
                $this->jsonUnslashesReturn(1,'还没添加技师',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取商户全部服务
     */
    public function getBusinessServices(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $businessServices=M('BusinessService')->where(['business_id'=>$id,'is_deleted'=>0])->field('price,name,good_at,id')->select();
            if($businessServices){
                $this->jsonReturn(1,'获取成功',$businessServices);
            }else{
                $this->jsonReturn(1,'没有服务',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取服务分类
     */
    public function getServiceCats(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $cat=M('Service')->where(['id'=>$id,'has_cats'=>1,'is_deleted'=>0])->find();
        if($cat){
            $cats=M('Service')->where(['pid'=>$id,'is_deleted'=>0])->field('name,id')->order('is_other')->select();
            if($cats){
                array_unshift($cats,['id'=>"$id",'name'=>'全部服务']);
                $this->jsonReturn(1,'获取成功',$cats);
            }else{
                $this->jsonReturn(1,'没有分类',[]);
            }
        }else{
            $this->jsonReturn(0,'没有该服务或该服务没有分类');
        }
    }

    /**
     * 获取服务列表
     */
    public function getServices(){
        $id=I('id',0,'intval');
        $type=I('type',0,'intval');
        $business_type=I('business_type',0,'intval');
        $order=I('order',0,'intval');
        $page=I('page',0,'intval');
        $lat=I('lat');
        $long=I('lng');
        if(!$id||!$order||!$page||!$lat||!$long){
            $this->jsonReturn(0,'请开启定位');
        }
        //有小汽车等区分
        if($type){
            //获取经营范围
            $scope=$this->getScopeTypeByType($type);
            $where['b.scope_id']=['in',$scope];
        }
        if($business_type){
            $where['b.type']=$business_type;
        }
        //排序
        switch ($order){
            case 2 :$orderName='distance';break;
            case 3 :$orderName='b.points DESC,distance';break;
            default : $orderName='bs.price,distance';
        }
        $start=($page-1)*$this->pageLimit;
        //获取城市名和id
        $region=$this->getSite($lat,$long);
        $region_id=$region['id'];
        //获取城市下区域id
        $region_ids=M('Region')->where(['pid'=>$region_id])->select();
        $region_ids=array_column($region_ids,'id');
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        //查询分类
        $cat=M('Service')->where(['id'=>$id,'is_deleted'=>0])->field('pid,id,has_cats')->find();
        if($cat){
            //顶级且有分类需查找全部子级
            if($cat['pid']==0&&$cat['has_cats']==1){
                $catIds=M('Service')->where(['pid'=>$id,'is_deleted'=>0])->select();
                $catIds=array_column($catIds,'id');
            }else{
                $catIds=[$id];
            }
            $where['bs.service_id']=['in',$catIds];
            $where['b.region_id']=['in',$region_ids];
            $where['bs.is_deleted']=0;
            $where['b.status']=1;
            $where['b.is_checked']=1;
            //20000米内
            $where["$sql"]=['ELT',200000];
            //查找商户服务,排序
            $services=M('BusinessService')
                ->alias('bs')
                ->join('LEFT JOIN __BUSINESS__ as b ON b.id=bs.business_id')
                ->field("$sql as distance,b.points,bs.price,b.visit,bs.name,b.logo,b.name as business_name,bs.id,bs.good_at,b.id as business_id,address")
                ->where($where)
                ->limit($start,$this->pageLimit+1)
                ->order($orderName)
                ->select();
            if($services){
                foreach ($services as &$service){
                    $service['logo']=empty($service['logo'])?'':$this->uploadPre.$service['logo'];
                }
                //检测是否是最后一页
                $services=$this->checkEndPage($services);
                $this->jsonUnslashesReturn(1,'获取成功',$services);
            }else{
                $this->jsonReturn(1,'没有服务',(object)[]);
            }
        }else{
            $this->jsonReturn(0,'分类不存在');
        }
    }

    /**
     * 服务详情关于商户部分
     */
    public function getServiceDetailsAboutBusiness(){
        $id=I('id',0,'intval');
        $lat=I('lat');
        $long=I('lng');
        if(!$id||!$lat||!$long){
            $this->jsonReturn(0,'请开启定位');
        }
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $business=M('Business')->where(['id'=>$id,'status'=>1,'is_checked'=>1])->field("id,name,points,visit,$sql as distance,address,phone,lat,`long` as lng,is_prepared")->find();
        if($business){
            $this->jsonReturn(1,'获取成功',$business);
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 服务详情关于轮播部分
     */
    public function getServiceDetailsAboutBanner(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'参数不存在');
        }
        $service=M('BusinessService')->where(['id'=>$id])->field("id,name,price,order_number")->find();
        if($service){
            $slides=M('BusinessServiceImage')->where(['business_service_id'=>$id,'type'=>1])->select();
            if($slides){
                //分割轮播和底部图
                foreach ($slides as $slide){
                    $service['banner'][]=['image'=>$this->uploadPre.$slide['image']];
                }
            }else{
                $service['banner']=[];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$service);
        }else{
            $this->jsonReturn(0,'无此服务');
        }
    }

    /**
     * 服务详情关于底部部分
     */
    public function getServiceDetailsAboutFooter(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'参数不存在');
        }
        $service=M('BusinessService')->where(['id'=>$id])->field("id,content")->find();
        if($service){
            $slides=M('BusinessServiceImage')->where(['business_service_id'=>$id,'type'=>2])->select();
            if($slides){
                //分割轮播和底部图
                foreach ($slides as $slide){
                    $service['footer'][]=['image'=>$this->uploadPre.$slide['image']];
                }
            }else{
                $service['footer']=[];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$service);
        }else{
            $this->jsonReturn(0,'无此服务');
        }
    }

    /**
     * 服务评价
     */
    public function getServiceComments(){
        $id=I('id',0,'intval');
        $page=I('page',0,'intval');
        if(!$id||$page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $comments=M('BusinessServiceComment')->where(['business_service_id'=>$id])
            ->field("username,avatar,star,content")->order('create_time DESC')->limit($start,$this->pageLimit+1)->select();
        if($comments){
            foreach ($comments as &$comment){
                $comment['avatar']=empty($comment['avatar'])?'':$this->uploadPre.$comment['avatar'];
            }
            //检测是否是最后一页
            $comments=$this->checkEndPage($comments);
            $this->jsonUnslashesReturn(1,'获取成功',$comments);
        }else{
            $this->jsonReturn(1,'暂无评价',(object)[]);
        }
    }

    /**
     * 通过搜索获取服务列表
     */
    public function getServicesBySearch(){
        $business_type=I('business_type',0,'intval');
        $order=I('order',0,'intval');
        $page=I('page',0,'intval');
        $lat=I('lat');
        $long=I('lng');
        $keyword=I('keyword');
        if(!$keyword){
            $this->jsonReturn(0,'缺少关键词');
        }
        if(!$order||!$page||!$lat||!$long){
            $this->jsonReturn(0,'请开启定位');
        }
        if($business_type){
            $where['b.type']=$business_type;
        }
        //排序
        switch ($order){
            case 2 :$orderName='distance';break;
            case 3 :$orderName='b.points DESC,distance';break;
            default : $orderName='bs.price,distance';
        }
        $start=($page-1)*$this->pageLimit;
        //获取城市名和id
        $region=$this->getSite($lat,$long);
        $region_id=$region['id'];
        //获取城市下区域id
        $region_ids=M('Region')->where(['pid'=>$region_id])->select();
        $region_ids=array_column($region_ids,'id');
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $where['b.region_id']=['in',$region_ids];
        $where['bs.is_deleted']=0;
        $where['bs.name']=['like',$keyword];
        $where['b.status']=1;
        $where['b.is_checked']=1;
        //20000米内
        $where["$sql"]=['ELT',200000];
        //查找商户服务,排序
        $services=M('BusinessService')
            ->alias('bs')
            ->join('LEFT JOIN __BUSINESS__ as b ON b.id=bs.business_id')
            ->field("$sql as distance,b.points,bs.price,b.visit,bs.name,b.logo,b.name as business_name,bs.id,bs.good_at,b.id as business_id,address")
            ->where($where)
            ->limit($start,$this->pageLimit+1)
            ->order($orderName)
            ->select();
        if($services){
            foreach ($services as &$service){
                $service['logo']=empty($service['logo'])?'':$this->uploadPre.$service['logo'];
            }
            //检测是否是最后一页
            $services=$this->checkEndPage($services);
            $this->jsonUnslashesReturn(1,'获取成功',$services);
        }else{
            $this->jsonReturn(1,'没有服务',(object)[]);
        }
    }

    /**
     * 获取活动轮播图
     */
    public function getBusinessActivitiesRecommend(){
        $recommends=M('BusinessActivityRecommend')->field('business_activity_id,image')->select();
        if($recommends){
            foreach ($recommends as &$recommend){
                $recommend['image']=$this->uploadPre.$recommend['image'];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$recommends);
        }else{
            $this->jsonReturn(1,'没有轮播图',[]);
        }
    }

    /**
     * 获取商户活动列表
     */
    public function getBusinessActivities(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        //分组排序，组内时间最近排序
        $sql=M('BusinessActivity')
            ->alias('ba')
            ->join('LEFT JOIN __BUSINESS__ as b ON ba.business_id=b.id')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY_CONTENT__ as bac ON ba.business_id=bac.business_id')
            ->where(['ba.is_deleted'=>0,'end_time'=>['EGT',time()],'b.status'=>1,'b.is_checked'=>1])
            ->field('ba.id,IFNULL(bac.`logo`,"") as logo,ba.business_id')
            ->order('ba.end_time')
            ->fetchSql()
            ->select();
        $model = new Model();
        $businessActivities=$model->query('SELECT * FROM ('.$sql.') AS a group by business_id limit '.$start.','.($this->pageLimit+1) );
        if($businessActivities){
            foreach ($businessActivities as $k=>&$businessActivity){
                $businessActivity['logo']=empty($businessActivity['logo'])?'':$this->uploadPre.$businessActivity['logo'];
                unset($businessActivities[$k]['business_id']);
            }
            $businessActivities=$this->checkEndPage($businessActivities);
            $this->jsonUnslashesReturn(1,'获取成功',$businessActivities);
        }else{
            $this->jsonReturn(1,'没有活动',(object)[]);
        }
    }

    /**
     * 根据活动id获取活动详情
     */
    public function getActivityDetailsById(){
        $id=I('id');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $businessActivity=M('BusinessActivity')->where(['id'=>$id,'is_deleted'=>0])->field('id,business_id,price,name,inventory,start_time,end_time')->find();
        if($businessActivity){
            $business=lt_get_normal_business_by_id($businessActivity['business_id']);
            if(!$business){
                $this->jsonReturn(0,'商户已被禁用');
            }
            //判断是否是最近的活动
            $businessActivityNearly=lt_get_nearly_simple_activity_by_business($business['id']);
            if(!$businessActivityNearly){
                $this->jsonReturn(0,'活动已结束');
            }
            if($businessActivityNearly['id']!=$id){
                $this->jsonReturn(0,'活动已结束');
            }
            $businessActivityContent=M('BusinessActivityContent')->where(['business_id'=>$business['id']])->field('content,image')->find();
            if(!$businessActivityContent){
                $businessActivity['content']='';
                $businessActivity['image']='';
            }else{
                $businessActivity['content']=empty($businessActivityContent['content'])?'':$businessActivityContent['content'];
                $businessActivity['image']=empty($businessActivityContent['image'])?'':$this->uploadPre.$businessActivityContent['image'];
            }
            unset($businessActivity['business_id']);
            $this->jsonUnslashesReturn(1,'获取成功',$businessActivity);
        }else{
            $this->jsonReturn(0,'该服务已结束');
        }
    }

    /**
     * 根据商户id获取活动详情
     */
    public function getActivityDetailsByBusiness(){
        $id=I('id');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_normal_business_by_id($id);
        if(!$business){
            $this->jsonReturn(0,'商户已被禁用');
        }
        $businessActivity=M('BusinessActivity')->where(['business_id'=>$id,'is_deleted'=>0,'end_time'=>['EGT',time()]])->order('end_time')->field('id,price,name,inventory,start_time,end_time')->find();
        if($businessActivity){
            $businessActivityContent=M('BusinessActivityContent')->where(['business_id'=>$id])->field('content,image')->find();
            if(!$businessActivityContent){
                $businessActivity['content']='';
                $businessActivity['image']='';
            }else{
                $businessActivity['content']=empty($businessActivityContent['content'])?'':$businessActivityContent['content'];
                $businessActivity['image']=empty($businessActivityContent['image'])?'':$this->uploadPre.$businessActivityContent['image'];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$businessActivity);
        }else{
            $this->jsonReturn(0,'还没有服务',(object)[]);
        }
    }
}